<template>
  <div class="rules-container">
    <el-card class="rules-card">
      <template #header>
        <div class="card-header">
          <h2>业务规则列表</h2>
          <el-button type="primary" @click="refreshRules">刷新</el-button>
        </div>
      </template>
      
      <el-table 
        :data="rules" 
        style="width: 100%" 
        :max-height="tableHeight"
        :row-class-name="tableRowClassName"
        highlight-current-row
      >
        <el-table-column type="index" label="ID" width="80" fixed="left" />
        <el-table-column prop="ruleName" label="规则名称" width="180" />
        <el-table-column prop="description" label="规则描述" min-width="300">
          <template #default="scope">
            <div class="description-cell">{{ scope.row.description }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="feelExpression" label="FEEL表达式" min-width="400">
          <template #default="scope">
            <div class="feel-expression">{{ scope.row.feelExpression }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              @click="viewRuleTree(scope.row)"
              :loading="loadingTree === scope.row.ruleName"
            >
              查看规则树
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 规则树对话框 -->
    <el-dialog
      v-model="showTreeDialog"
      title="规则树"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-loading="loadingTree">
        <el-tree
          :data="ruleTree"
          :props="defaultProps"
          node-key="id"
          default-expand-all
        >
          <template #default="{ data }">
            <div class="custom-tree-node">
              <span class="node-type">{{ data.nodeType }}</span>
              <span class="node-text">{{ data.text }}</span>
            </div>
          </template>
        </el-tree>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api'

interface Rule {
  ruleName: string
  description: string
  feelExpression: string
}

interface AstNode {
  nodeType: string
  text: string
  children?: AstNode[]
  id?: string
}

const rules = ref<Rule[]>([])
const tableHeight = ref(600)
const showTreeDialog = ref(false)
const ruleTree = ref<AstNode[]>([])
const loadingTree = ref<string | null>(null)

const defaultProps = {
  children: 'children',
  label: 'text'
}

const updateTableHeight = () => {
  // 设置表格高度为视窗高度的80%
  tableHeight.value = window.innerHeight * 0.8
}

const tableRowClassName = ({ row, rowIndex }: { row: any; rowIndex: number }) => {
  return 'table-row'
}

const fetchRules = async () => {
  try {
    const response = await api.get('/rule/getAllRules')
    rules.value = response.data
  } catch (error) {
    console.error('获取规则失败:', error)
    ElMessage.error('获取规则失败')
  }
}

const refreshRules = () => {
  fetchRules()
  ElMessage.success('刷新成功')
}

// 查看规则树
const viewRuleTree = async (rule: Rule) => {
  loadingTree.value = rule.ruleName
  try {
    const response = await api.post('/rule/checkRuleASTNode', {
      ruleName: rule.ruleName,
      description: rule.description,
      feelExpression: rule.feelExpression
    })
    
    // 为树节点添加唯一ID
    const addIdsToTree = (node: AstNode, parentId: string = ''): AstNode => {
      const id = parentId ? `${parentId}-${node.nodeType}` : node.nodeType
      const newNode = { ...node, id }
      if (node.children) {
        newNode.children = node.children.map(child => addIdsToTree(child, id))
      }
      return newNode
    }

    ruleTree.value = [addIdsToTree(response.data)]
    showTreeDialog.value = true
  } catch (error) {
    console.error('获取规则树失败:', error)
    ElMessage.error('获取规则树失败')
  } finally {
    loadingTree.value = null
  }
}

onMounted(() => {
  fetchRules()
  updateTableHeight()
  window.addEventListener('resize', updateTableHeight)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateTableHeight)
})
</script>

<style scoped>
.rules-container {
  padding: 20px;
  width: 80%;
  margin: 0 auto;
}

.rules-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5em;
  color: #303133;
}

.description-cell,
.feel-expression {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
  padding: 8px 0;
}

.description-cell {
  max-width: 300px;
}

.feel-expression {
  max-width: 400px;
}

/* 表格行样式 */
:deep(.table-row) {
  transition: all 0.3s ease;
}

:deep(.table-row:hover) {
  background-color: #f5f7fa !important;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .rules-container {
    width: 90%;
  }
}

@media screen and (max-width: 768px) {
  .rules-container {
    width: 95%;
    padding: 10px;
  }
}

/* 规则树样式 */
.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
}

.node-type {
  background-color: #409EFF;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
}

.node-text {
  color: #606266;
  font-size: 14px;
  max-width: 500px;
  word-break: break-all;
}

/* 对话框样式 */
:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #EBEEF5;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
}

:deep(.el-tree-node__children) {
  padding-left: 20px;
}
</style> 